package org.techmore.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class ImageDownloadReturnPathHandler implements Runnable{
	
	private String httpPath;
	private Handler progressHandler;
	private String fileName;
	private int toWidth;
	private int toHight;
	public ImageDownloadReturnPathHandler(String httpPath,Handler progressHandler,String fileName,int toWidth,int toHight){
		this.httpPath = httpPath;
		this.progressHandler = progressHandler;
		this.fileName = fileName;
		this.toHight = toHight;
		this.toWidth = toWidth;
	}

	private File fileDirectory = getImageCacheDirectory();
	@Override
	public void run() {
		File imgFile = new File(fileDirectory, fileName);
		if(imgFile.exists()){
			sendMsg(imgFile.getPath());
		}else{
			downLoadImage(httpPath);
		}
		
	}
	
	private Bitmap bitmap = null;
	private void downLoadImage(String httpPath) {
		FileOutputStream fos = null;
		InputStream fis = null;
		HttpURLConnection httpUrlConnection = null;
		File imageFile = null;
		try {
			URL httpUrl = new URL(httpPath);
			
			if(!fileDirectory.exists()){
				fileDirectory.mkdirs();
			}
			imageFile = new File(fileDirectory,fileName);
			httpUrlConnection = (HttpURLConnection) httpUrl.openConnection();
			int httpState = 404;
			try {
				httpState=httpUrlConnection.getResponseCode();
			} catch (ConnectException e) {
				Log.e("downloadImage",e.getMessage());
			}
			if(httpState<400){
				if(imageFile.exists()){
					imageFile.delete();
				}
				fos = new FileOutputStream(imageFile);
				httpUrlConnection.connect();
				fis = httpUrlConnection.getInputStream();
				int i = 0;
				byte[] b = new byte[64];
				while((i=fis.read(b)) != -1){
					fos.write(b, 0, i);
				}
			}else{
				
			}
		} catch (MalformedURLException e) {
			Log.e("downloadImage",e.getMessage());
		} catch (FileNotFoundException e) {
			Log.e("downloadImage",e.getMessage());
		} catch (IOException e) {
			Log.e("downloadImage",e.getMessage());
		}finally{
			try {
				if(fis != null){
					fis.close();
				}
				if(fos != null){
					fos.flush();
					fos.close();
				}
				httpUrlConnection.disconnect();
			} catch (IOException e) {
				Log.e("downloadImage",e.getMessage());
			}
		}
		
		bitmap = BitmapFactory.decodeFile(imageFile.getPath());
		if(bitmap.getWidth()>toWidth || bitmap.getHeight()>toHight){
			Matrix matrix = new Matrix();
			float width = Float.intBitsToFloat(toWidth)/Float.intBitsToFloat(bitmap.getWidth());
			float height = Float.intBitsToFloat(toHight)/Float.intBitsToFloat(bitmap.getHeight());
			matrix.preScale(width,height);
			Bitmap bitmapNew = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
			FileOutputStream fileOutputStream = null;
			try {
				fileOutputStream = new FileOutputStream(new File(imageFile.getPath()));
				bitmapNew.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
			} catch (FileNotFoundException e) {
				Log.e("downloadImage",e.getMessage());
			}finally{
				if(null != fileOutputStream){
					try {
						fileOutputStream.flush();
						fileOutputStream.close();
					} catch (IOException e) {
						Log.e("downloadImage",e.getMessage());
					}
				}
			}
		}
		
		
		
		sendMsg(imageFile.getPath());
	}
	
	private void sendMsg(String path) {
		Message msg = new Message();
		msg.obj = path;
		progressHandler.sendMessage(msg);
	}
	
	private File getImageCacheDirectory(){
//		if(!isSdcardPrepared()){
			return new File(Environment.getDataDirectory(), PropertiesUtil.getInstance().getValue("qr_img_folder_cache"));
//		}else{
//			return new File(Environment.getExternalStorageDirectory(), "/service/com.techmore.pls/xmlCache");
//		}
	}
	
//	private boolean isSdcardPrepared(){
//		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
//	}
	
	

}
